package me.yangbajing.helper

import org.joda.time._
import net.liftweb.http.LiftRules
import java.io.{InputStreamReader, InputStream, FileInputStream}
import me.yangbajing.common.{MeAdapter, MeConfig}

object MeHelpers {

  def timeDescription(at: DateTime): String = {
    val now = DateTime.now()

    yearsBetween(at, now).map(i => s"于${i}年前发布") orElse
      monthsBetween(at, now).map(i => s"于${i}个月前发布") orElse
      weeksBetween(at, now).map(i => s"于${i}周前发布") orElse
      daysBetween(at, now).map(i => s"于${i}天前发布") orElse
      hoursBetween(at, now).map(i => s"于${i}小时前发布") orElse
      minutesBetween(at, now).map(i => s"于${i}分钟前发布") getOrElse
      "刚发布"
  }

  def yearsBetween(at: DateTime, now: DateTime) =
    _between(Years.yearsBetween(at, now).getYears)

  def monthsBetween(at: DateTime, now: DateTime) =
    _between(Months.monthsBetween(at, now).getMonths)

  def weeksBetween(at: DateTime, now: DateTime) =
    _between(Weeks.weeksBetween(at, now).getWeeks)

  def daysBetween(at: DateTime, now: DateTime) =
    _between(Days.daysBetween(at, now).getDays)

  def hoursBetween(at: DateTime, now: DateTime) =
    _between(Hours.hoursBetween(at, now).getHours)

  def minutesBetween(at: DateTime, now: DateTime) =
    _between(Minutes.minutesBetween(at, now).getMinutes)

  @inline
  private def _between(days: Int): Option[Int] =
    if (days > 0) Some(days) else None

  import org.json4s._
  import org.json4s.native._
  import org.json4s.ext.{EnumNameSerializer, JodaTimeSerializers}

  implicit val jsonFormats = DefaultFormats + new EnumNameSerializer(MeAdapter) ++ JodaTimeSerializers.all

  lazy val config: MeConfig =
    LiftRules.doWithResource("/WEB-INF/me-config.json")(in => config(in)) openOr
      config(new FileInputStream("/data/workspace/yangbajing-me/app/me/src/main/webapp/WEB-INF/me-config.json"))

  def config(in: InputStream, charset: String = "UTF-8"): MeConfig =
    JsonParser.parse(new InputStreamReader(in, charset)).extract[MeConfig]

}
